<template>
  <van-popup
    v-model:show="shows"
    @close="onClickLeft"
    round
    position="bottom"
    :z-index="zIndex"
    :style="{ height: '95%' }"
  >
    <div class="contents">
      <van-nav-bar :title="title" left-arrow @click-left="onClickLeft" />
      <div class="searchBox">
        <div class="search-left">
          <van-field
            @click="openCity"
            disabled
            v-model="citys.name"
            :style="{ padding: '0px 10px', textAlign: 'center' }"
            :placeholder="placeholder"
          >
            <template #button>
              <van-icon name="arrow-down" />
            </template>
          </van-field>
        </div>
        <div class="search-right">
          <van-field
            v-model="qstr"
            clearable
            :placeholder="placeholder"
            @update:model-value="onSearch"
            :style="{ padding: '0px 10px', borderLeft: '1px solid #eeeeee' }"
          >
            <template #button>
              <span class="search-cancer">取消</span>
            </template>
          </van-field>
        </div>
      </div>
      <div class="poi-mod" v-if="showMode">
        <van-grid
          clickable
          :column-num="2"
          direction="horizontal"
          icon-size="22px"
        >
          <van-grid-item
            @click="getMineAddress"
            icon="location-o"
            text="我的位置"
          >
            <template #text>
              <div class="mode-title">
                <p>我的位置</p>
                <p v-if="mineAddress">{{ mineAddress }}</p>
              </div>
            </template>
          </van-grid-item>
          <van-grid-item
            icon="apps-o"
            text="常用地址"
            @click="openCarCommonlyAddress"
          >
            <template #text>
              <div class="mode-title">
                <p>常用地址</p>
                <p>选择常用地址</p>
              </div>
            </template>
          </van-grid-item>
        </van-grid>
      </div>
      <div class="poi-list" v-if="cityData.length">
        <template v-for="(ktem, k) in cityData" :key="k + 'key'">
          <div class="list-item" @click="clickPoi(ktem)">
            <div class="item-icon"><van-icon name="location-o" /></div>
            <div class="item-cont">
              <p class="cont-name">{{ ktem.name }}</p>
              <p class="cont-detail" v-if="ktem.address">
                <span class="cont-type" v-if="setPoiType(ktem.type)">{{
                  setPoiType(ktem.type)
                }}</span>
                {{ ktem.address }}
              </p>
            </div>
          </div>
        </template>
        <p class="clear-history" v-if="!qstr">
          <span @click="clearHistory">清空历史记录</span>
        </p>
      </div>
      <div class="poi-no-data" v-else>
        <p v-if="qstr">
          未搜索到该地址 <br />
          请更换城市或者更换地址信息进行搜索
        </p>
        <p v-else>
          暂无历史记录
        </p>
      </div>
    </div>
  </van-popup>
  <!--  城市选择-->
  <CheckCity
    :zIndex="zIndex + 500"
    v-model:show="showCity"
    @change="changeCity"
  />
</template>

<script>
import CheckCity from "/@/components/CheckCity/CheckCity.vue";
import {
  getAddress,
  getPoiList,
  nglatToAddress,
  addressInfo
} from "/@/assets/map/searchCarMap/getMapData.js";
import storage from "../../assets/util/storage";
import { Toast } from "vant";
import { getCurrentInstance, onMounted, reactive, toRefs, watch } from "vue";

export default {
  name: "SearchPoi",
  components: {
    CheckCity
  },
  props: {
    show: Boolean, // 是否显示
    zIndex: {
      type: Number,
      default: () => {
        return 1000;
      }
    },
    showMode: {
      type: Boolean,
      default: () => {
        return true;
      }
    },
    title: {
      type: String,
      default: () => {
        return "选择上车点";
      }
    },
    placeholder: {
      type: String,
      default: () => {
        return "您要去哪儿";
      }
    }
  },
  emits: ["update:show", "change"],
  setup(props) {
    const { proxy } = getCurrentInstance();
    const storageKey = `appCarPoiList_${localStorage.memberId || ""}`;
    const pageData = reactive({
      cityData: [],
      qstr: "",
      showCity: false,
      shows: props.show,
      mineAddress: "",
      citys: {
        // 城市信息
        name: "北京市", // 城市名称
        code: "010", // 城市编号
        address: "", // 详细地址
        flat: "", // 地址纬度
        flng: "" // 地址精度
      }
    });
    // 打开弹窗
    watch(
      () => props.show,
      item => {
        pageData.qstr = "";
        pageData.cityData = storage.getItem(storageKey) || [];
        pageData.shows = item;
      },
      { immediate: true }
    );
    onMounted(() => {
      pageMethods.initDefault();
    });
    const pageMethods = {
      setPoiType(type) {
        if (!type) return type;
        const types = type.split(";");
        if (types.length) {
          return types[types.length - 1];
        }
        return "";
      },
      initDefault() {
        // 初始化默认的我的位置
        const defaultAddress = window.DEFAULTADDRESS || {};
        if (defaultAddress.cityName && defaultAddress.cityCode) {
          pageData.citys.name = defaultAddress.cityName;
          pageData.citys.code = defaultAddress.cityCode;
        }
        pageData.mineAddress = pageData.citys.address || "";
        pageData.cityData = storage.getItem(storageKey) || [];
      },
      onClickLeft() {
        proxy.$emit("update:show", false);
      },
      onchange(data) {
        pageMethods.onClickLeft();
        proxy.$emit("change", data);
      },
      changeCity(data) {
        pageData.citys.name = data.CityName || "";
        pageData.citys.code = data.CityDistrict || "";
        pageData.qstr = "";
        pageMethods.onSearch("");
      },
      openCity() {
        pageData.showCity = true;
      },
      clickPoi(poi) {
        // 请注意：当城市是省直辖县时返回为空，以及城市为北京:010、上海:021、天津:022、重庆:023四个直辖市时，该字段返回为空当城市名称取不到的时候取(province)；
        const lnglat = poi.location || {};
        if (!poi.locationS) {
          poi.locationS = {
            lat: lnglat.lat || "", // 地址纬度
            lng: lnglat.lng || "" // 地址精度
          };
        }
        // 获取到了城市
        const citys = {
          address: poi.name || "",
          flat: poi.locationS.lat || "", // 地址纬度
          flng: poi.locationS.lng || "", // 地址精度
          code: poi.cityCode,
          name: poi.cityName
        };
        const perform = () => {
          Object.assign(pageData.citys, citys);
          pageData.citys["simple_address"] = poi.address || "";
          pageMethods.selectPoi(poi);
        };
        if (!poi.cityCode || !poi.cityName) {
          // 选择POI
          proxy.$store.commit("TOGGLE_LOADING", true);
          nglatToAddress(lnglat, nowCity => {
            proxy.$store.commit("TOGGLE_LOADING", false);
            const nowCitys = addressInfo(nowCity, lnglat);
            citys.name = nowCitys.cityName || "";
            citys.code = nowCitys.cityCode || "";
            poi.cityCode = nowCitys.cityCode || "";
            poi.cityName = nowCitys.cityName || "";
            perform();
          });
          return;
        }
        perform();
      },
      setStorege(poi) {
        // 设置历史记录
        let list = storage.getItem(storageKey) || [];
        let isAdd = false;
        list.forEach(item => {
          if (item.name === poi.name) isAdd = true;
        });
        !isAdd && list.push(poi);

        storage.setItem(storageKey, list);
      },
      clearHistory() {
        storage.setItem(storageKey, []);
        pageData.cityData = [];
      },
      selectPoi(poi) {
        pageMethods.setStorege(poi);
        proxy.$emit("change", pageData.citys, poi);
        proxy.$emit("update:show", false);
      },
      /** 获取当前地址 */
      getMineAddress() {
        if (sessionStorage.isNative == "1") {
          pageMethods.getLocationCity();
          return;
        }
        proxy.$store.commit("TOGGLE_LOADING", true);
        getAddress((citys, re) => {
          proxy.$store.commit("TOGGLE_LOADING", false);
          if (citys.flng && citys.flat && citys.address) {
            pageMethods.minePoi(citys);
          } else {
            Toast("获取当前位置失败");
          }
        });
      },
      minePoi(citys) {
        pageData.mineAddress = citys.address;
        Object.assign(pageData.citys, citys);
        const nowCity = pageData.citys;
        const poi = {
          name: nowCity.address || "",
          locationS: { lng: nowCity.flng, lat: nowCity.flat },
          address: citys.cityName || "",
          cityCode: nowCity.cityCode || "",
          cityName: nowCity.cityName || ""
        };
        pageData.citys.name = citys.cityName;
        pageData.citys.code = citys.cityCode;
        pageMethods.selectPoi(poi);
        if (!pageData.qstr) {
          pageData.cityData = storage.getItem(storageKey) || [];
        }
      },
      getLocationCity() {
        proxy.$store.commit("TOGGLE_LOADING", true);
        JSBridge.call("getCurrentLocation", "", data => {
          const lnglat = {
            lat: data.latitude,
            lng: data.longitude
          };
          nglatToAddress(lnglat, res => {
            proxy.$store.commit("TOGGLE_LOADING", false);
            const citys = addressInfo(res, lnglat);
            if (citys.flng && citys.flat && citys.address) {
              pageMethods.minePoi(citys);
            } else {
              Toast("获取当前位置失败");
            }
          });
        });
      },
      openCarCommonlyAddress() {
        // 打开常用地址
        proxy.$router.push({
          path: "/home/carCommonlyAddress",
          query: {}
        });
      },
      onSearch(val) {
        const citys = pageData.citys;
        getPoiList(val, citys, data => {
          const res = data || {};
          const poiData = res.poiList || {};
          pageData.cityData = poiData.pois || [];
          if (!val) {
            pageData.cityData = storage.getItem(storageKey) || [];
          }
        });
      }
    };
    return {
      ...toRefs(pageData),
      ...pageMethods,
      ...props
    };
  }
};
</script>

<style scoped lang="less">
.searchBox {
  overflow: auto;
  & > div {
    float: left;
    line-height: 30px;
    padding: 10px 0;
  }
  .search-left {
    width: 110px;
    text-align: center;
    font-size: 16px;
    :deep(input) {
      text-align: center;
    }
  }
  .search-right {
    width: calc(100% - 110px);
    .search-cancer {
      display: inline-block;
      border-left: 1px solid #eeeeee;
      padding-left: 10px;
      color: #999999;
    }
  }
}
.poi-mod {
  :deep(.mode-title) {
    p {
      padding-left: 5px;
    }
    p:last-child {
      font-size: 12px;
      margin-top: 5px;
      color: #999999;
    }
    p:first-child {
      color: #333333;
      font-size: 14px;
      font-weight: bold;
    }
  }
}

.poi-list {
  font-size: 14px;
  .list-item {
    padding: 10px;
    border-bottom: 1px solid #eeeeee;
    &:last-child {
      border-bottom: none;
    }
    & > div {
      display: inline-block;
    }
    .item-icon {
      width: 40px;
      text-align: center;
      vertical-align: top;
      font-size: 18px;
      color: #666666;
    }
    .item-cont {
      width: calc(100% - 45px);
      .cont-name {
        color: #333333;
      }
      .cont-detail {
        color: #999999;
        margin-top: 7px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        font-size: 13px;
        .cont-type {
          padding-right: 5px;
        }
      }
    }
  }
}

.poi-no-data {
  p {
    font-size: 17px;
    text-align: center;
    margin-top: 70px;
    line-height: 30px;
    color: #999999;
  }
}
.clear-history {
  text-align: center;
  line-height: 50px;
  color: #1a6eff;
  cursor: pointer;
}
:deep(.van-field__control:disabled) {
  color: #323233;
  -webkit-text-fill-color: #323233;
}
</style>
